package org.example.app.service.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class EmailUtil {
    // QQ邮箱SMTP配置
    private static final String SMTP_HOST = "smtp.qq.com";
    private static final int SMTP_PORT = 587;  // 或 465（需修改SSL配置）
    private static final String SMTP_USER = "2905915957@qq.com";  // 发件邮箱
    private static final String SMTP_PASSWORD = "ybtqujfidcxzdehj";  // 邮箱授权码

    /**
     * 发送邮件
     * @param toEmail 收件人邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     * @throws MessagingException 发送失败时抛出异常
     */
    public static void sendEmail(String toEmail, String subject, String content) throws MessagingException {
        // 1. 配置SMTP服务器参数
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");  // 使用TLS加密
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);

        // 2. 创建邮件会话
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SMTP_USER, SMTP_PASSWORD);
            }
        });

        // 3. 构建邮件对象
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(SMTP_USER));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject(subject);
        message.setText(content);

        // 4. 发送邮件
        Transport.send(message);
    }
}
